package com.edevp.common.core.dto;

import com.edevp.common.core.constant.CommonConstants;
import com.edevp.common.core.util.CommonUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Map;

/**
 * 消息返回体
 *
 * @author Lean
 * @create 2019-10-31 2:13 PM
 **/
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@JsonInclude(value = JsonInclude.Include.NON_NULL)
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    @Getter
    @Setter
    private int code;

    @Getter
    @Setter
    private String msg;


    @Getter
    @Setter
    private T data;


    @Getter
    @Setter
    private String uri;

    public static <T> R<T> ok() {
        return restResult(null, CommonConstants.SUCCESS, null);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, CommonConstants.SUCCESS, null);
    }

    public static <T> R<T> error() {
        return restResult(null, CommonConstants.FAIL, null);
    }

    public static <T> R<T> error(String msg) {
        return restResult(null, CommonConstants.FAIL, msg);
    }

    public static <T> R<T> error(T data) {
        return restResult(data, CommonConstants.FAIL, null);
    }
    public static <T> R<T> error(int code) {
        return restResult(null, code, null);
    }

    /*public Map<String,Object> toMap() {
        return BeanUtil.beanToMap(this);
    }*/


    /*public static <T> R<T> exception(int code,String msg) {
        return restResult(null, code, msg, SessionUtil.getCurrentRequestURI());
    }*/

    public static <T> R<T> error(int code,String msg) {
        return restResult(null, code, msg);
    }

    public static <T> R<T> error(int code,String msg,T data) {
        return restResult(data, code, msg);
    }
    public static <T> R<T> error(int code,String msg,String uri) {
        return restResult(null, code, msg,uri);
    }

    public static <T> R<T> error(int code,String msg,T data,String uri) {
        return restResult(data, code, msg,uri);
    }


    private static <T> R<T> restResult(T data, int code, String msg) {
        return restResult(data,code,msg,null);
    }

    private static <T> R<T> restResult(T data, int code, String msg,String uri) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        apiResult.setUri(uri);
        if(CommonUtil.isNull(msg)){
            //apiResult.setMsg(LocalUtil.get(String.valueOf(code)));
        }
        if(CommonUtil.isNull(uri)){
            //apiResult.setUri(SessionUtil.getCurrentRequestURI());
        }
        if(CommonUtil.isNull(apiResult.getMsg())){
            apiResult.setMsg(null);
        }
        return apiResult;
    }
}